<template>
  <div class="editor-config-btn">
    <slot>
      <template v-if="!showTypeBtn">
        <a-button type="primary" @click="createWorkHandle" :loading="loading">
          创建设计
        </a-button>
        <a-button type="primary" @click="goMyWorkHandle"> 我的作品 </a-button>
      </template>
      <template v-else>
        <a-button
          type="primary"
          @click="preViewWorkHandle"
          :loading="previewLoading"
        >
          预览和设置
        </a-button>
        <a-button type="primary" @click="saveWorkHandle" :loading="loading">
          保存
        </a-button>
        <a-button
          type="primary"
          @click="publishWorkHandle"
          :loading="publishLoading"
        >
          发布
        </a-button>
      </template>
    </slot>
    <a-modal v-model:open="open" title="发布成功" :footer="false" width="700px">
      <PublishWorkTemplate :workId="workId" :workUrl="workUrl" v-model="open" />
    </a-modal>

    <PreviewWork
      :workId="workId"
      v-model="openDrawer"
      v-model:publishBtnLoading="publishBtnLoading"
      @publish="publishWorkHandle"
    />
  </div>
</template>

<script setup lang="ts">
import useGlobalStore from '@/store/modules/globalStore'
import useEditorStore from '@/store/modules/editorStore'
import useSaveWork from '@/hooks/useSaveWork'
import PublishWorkTemplate from './PublishWorkTemplate.vue'
import PreviewWork from './PreviewWork.vue'
import { useRoute, useRouter } from 'vue-router'
import { computed, nextTick, ref, watch } from 'vue'
import {
  createWorkAPI,
  publishWorkOrTemplateAPI,
  uploadImageAPI,
} from '@/request/modules/work'
import { nanoid } from 'nanoid'
import html2canvas from 'html2canvas'
import { message } from 'ant-design-vue'
defineOptions({
  name: 'EditorConfigBtn',
})
const route = useRoute()
const router = useRouter()
const editorStore = useEditorStore()
const workUrl = ref('')
const workId = computed(() => {
  return editorStore.workId
})

const { saveWork } = useSaveWork()
const globalStore = useGlobalStore()
const showTypeBtn = computed(() => {
  return route.name === 'editor' ? true : false
})
const loading = computed(() => {
  return globalStore.isLoading
})
const previewLoading = ref(false)
const open = ref(false)
const openDrawer = ref(false)
const publishLoading = ref(false)
const createWorkHandle = async () => {
  const result = await createWorkAPI()
  const { _id } = result.data?.data || {}
  if (_id) {
    router.push({
      name: 'editor',
      params: {
        id: _id,
      },
    })
  }
}
const publishBtnLoading = ref(false)
const publishWorkHandle = async () => {
  // 设置发布按钮加载状态为true
  publishLoading.value = true
  // 获取canvas元素
  const el = document.getElementById('canvas-area') as HTMLElement
  //取消选择
  editorStore.setActiveComponent('')
  //去除bo x-shadow属性
  globalStore.setCanvasFix(true)
  // 等待页面更新
  nextTick(() => {
    // 将canvas元素转换为图片
    html2canvas(el, {
      width: 375,
      useCORS: true,
      scale: 3,
    })
      .then(async (canvas) => {
        // 将图片转换为blob
        canvas.toBlob(async (blob) => {
          // 创建FormData对象
          const formData = new FormData()
          // 将blob添加到FormData中
          formData.append('file', blob as Blob, nanoid(6) + '.png')
          // 上传图片
          const result = await uploadImageAPI(formData)
          // 获取上传结果
          const { data } = result.data
          // 如果上传成功
          if (Array.isArray(data) && data.length > 0) {
            // 获取上传的图片
            const coverImage = data[0]
            // 更改页面数据
            editorStore.changePageData(
              { key: 'coverImg', value: coverImage },
              true
            )
            // 保存作品
            await saveWork()
            // 发布作品或模板
            const result = await publishWorkOrTemplateAPI({
              id: workId.value,
              isPublic: true,
            })
            // 获取作品链接
            workUrl.value = result.data?.data || ''
            // 打开链接
            open.value = true
            // 关闭抽屉
            openDrawer.value = false
            // 设置发布按钮加载状态为false
            publishBtnLoading.value = false
          }
        })
      })
      .finally(() => {
        //恢复box-shadow属性
        globalStore.setCanvasFix(false)
        // 设置发布按钮加载状态为false
        publishLoading.value = false
      })
  })
}
const preViewWorkHandle = async () => {
  previewLoading.value = true
  await saveWork()
  openDrawer.value = true
  previewLoading.value = false
}
const saveWorkHandle = async () => {
  await saveWork()
  message.success('保存成功')
}
const goMyWorkHandle = () => {
  router.push({
    name: 'myWork',
  })
}
</script>

<style scoped></style>
